FileIO = {}

function FileIO.getHome()
    return os.getenv("HOME")
end

function FileIO.getHomeDirectory()
    return os.getenv("HOME") .. "/"
end

function FileIO.getDocumentDirectory()
    return os.getenv("HOME") .. "/Documents/"
end

function FileIO.getTmpDirectory()
    return os.getenv("HOME") .. "/tmp/"
end

function FileIO.getLibraryDirectory()
    return os.getenv("HOME") .. "/Library/"
end

-- 创建目录(开启os.execute后可以使用)
-- 成功返回true，失败返回false
function FileIO.createDirectory(dir)
    if os.execute then
        local result = os.execute("mkdir " .. dir)
        if result then
            return true
        else
            return false
        end
    else
        return false
    end
end

function FileIO.delete(dir)
    return os.remove(dir)
end

function FileIO.isFileExist(fileName)
    local file,error = io.open(fileName,"w+")
    if file then
        file:close()
        return true
    else
        return false
    end
end

-- 写文本
function FileIO.saveTextFile(fileName,text)
    local file,error = io.open(fileName,"w+")
    if not file then
        return false,error
    end
    file:write(text)
    file:close()
    return true
end

-- 读文本
function FileIO.readTextFile(fileName)
    local file,error = io.open(fileName,"r")
    if not file then
        return nil,error
    end
    local text = file:read("*a")
    file:close()
    return text
end

-- 返回打开的文件对象
function FileIO.openFile(fileName,mode)
    local file,error = io.open(fileName,mode)
    if not file then
        return nil,error
    end
    return file
end


FileIOClass = class()

function FileIOClass:init()
    self.path = ""
end

function FileIOClass:setPath(path)
    self.path = path
end

function FileIOClass:setPathToDocuments()
    self.path = FileIO.getDocumentDirectory()
end

function FileIOClass:saveTextFile(fileName,text)
    return FileIO.saveTextFile(self.path .. fileName,text)
end

function FileIOClass:readTextFile(fileName)
    return FileIO.readTextFile(self.path .. fileName)
end

function FileIOClass:createDirectory(dir)
    return FileIO.createDirectory(self.path .. dir)
end

function FileIOClass:delete(dir)
    return FileIO.delete(self.path .. dir)
end

function FileIOClass:isFileExist(fileName)
    return FileIO.isFileExist(self.path .. fileName)
end

function FileIOClass:openFile(fileName,mode)
    return FileIO.openFile(self.path .. fileName,mode)
end
